import express from 'express'
import expressWs from 'express-ws'
import { Result} from '../config/Result.js'
import {logger} from '../utils/logger.js'

const router = express.Router()

// @ts-ignore
expressWs(router);

/**
 * @apiDefine websocket
 * WEBSOCKET模块
 */

/**
 * @api {ws} /ws/connect 链接WS
 * @apiDescription WebSocket 实时通信
 * @apiVersion 1.0.0
 * @apiName websocketConnect
 * @apiGroup websocket
 * @apiExample {js} webSocket 客户端示例:
 * const ws = new WebSocket('ws://example.com/ws/connect');
 * ws.onmessage = (event) => {
 *   console.log(JSON.parse(event.data));
 * };
 * @apiUse websocket
 */
router.ws('/connect', function (ws, req) {
	ws.send(JSON.stringify(Result.success(`你成功连接了地址为 '/ws/connect' 的websocket`)))
	ws.on('close', function() {
		logger.log('websocket关闭');
	});
	ws.on('error', function(err) {
		logger.error('websocket发生异常', err.stack);
	})
	ws.on('message', function(msg) {
		logger.log('websocket收到消息', msg);
		ws.send(JSON.stringify(Result.success(`已接收到你的消息`)))
	});
})


export default router
